package pdi.IO;


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.lang3.time.StopWatch;

import pdi.core.Image;


import au.com.bytecode.opencsv.CSVReader;

public class CSVImgReader extends ImgReader{

	protected String csvFile;
	protected char delimiter = ',';
	protected CSVReader csv;


	public CSVImgReader(String csvFile) {
		this(csvFile,',');

	}

	public CSVImgReader(String csvFile, char delimiter) {
		super();
		this.csvFile = csvFile;
		this.delimiter = delimiter;
	}

	@Override
	public void open() {		

		//check if exist
		File xmlFile = new File(csvFile);
		if(!xmlFile.exists())
			throw new IllegalArgumentException("There isn't a csv file on the requested path");

		try{
			csv = new CSVReader(new FileReader(csvFile), delimiter,'"', '\0');			
			String[] header = csv.readNext();

		} catch (IOException e) {
			e.printStackTrace();
		}		

	}

	@Override
	public void close() {
		try {
			csv.close();
			csv = null;
		} catch (IOException e) {			
			e.printStackTrace();
		}
	}

	@Override
	public Image readNext() {

		if(csv == null)
			throw new IllegalArgumentException("UnOpen reader or empty csv");

		Image img = null;


		try {
			
			String[] fields = csv.readNext();

			if (fields!= null) {
				img = new Image();
				img.setName(fields[0]);
				img.setPath(fields[1]);
				img.setWidth(Integer.parseInt(fields[2]));
				img.setHeight(Integer.parseInt(fields[3]));

				
				
				double[] featureVector = new double[fields.length - 5];	        
				for (int idx = 5, fvIdx = 0; idx < fields.length ; idx++, fvIdx++){
					featureVector[fvIdx] = Double.parseDouble(fields[idx]); 
				}
				img.setFeatureVector(featureVector);	
				
				
			}
		} catch (IOException e) {			
			e.printStackTrace();
		}

		return img;
	}

	@Override
	public List<Image> readAll() {
		open();
		
		//read all images and put in a list
		List<Image> ret = new ArrayList<Image>();
		Image img = null;
		while((img = readNext()) != null){		
			ret.add(img);
			if(ret.size() % 1000 == 0){
				System.out.println(ret.size() + " images were read");
			}
		}
		close();
		
		return ret;
	}

}
